package com.neu.credit.creditscore.common.utils;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;

public class RandomIdGenerator {

    // 字符集，包含字母和数字
    private static final String CHAR_SET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    private static final int ID_LENGTH = 8; // 生成的编号长度
    private Set<String> generatedIds = new HashSet<>(); // 用于存储已生成的编号，确保不重复

    // 随机生成一个不重复的编号
    public String generateUniqueId() {
        Random random = new Random();
        String id;

        // 确保生成的编号不重复
        do {
            id = generateRandomId(random);
        } while (generatedIds.contains(id)); // 如果生成的编号已经存在，则重新生成

        // 将生成的编号添加到集合中
        generatedIds.add(id);
        return id;
    }

    // 根据字符集生成随机编号
    private String generateRandomId(Random random) {
        StringBuilder idBuilder = new StringBuilder(ID_LENGTH);
        for (int i = 0; i < ID_LENGTH; i++) {
            int index = random.nextInt(CHAR_SET.length());
            idBuilder.append(CHAR_SET.charAt(index));
        }
        return idBuilder.toString();
    }
}
